package org.ym.tools;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.ym.tools.adapter.*;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;

/**
 * @author ym
 * @date 2022-06-06 16:10:25
 */
public class GsonTool {
    public static final String EMPTY = "";

    private GsonTool(){
    }

    /**
     * 唯一实例
     */
    private static Gson gsonInstance;
    /**
     * 锁
     */
    private static final Object LOCK = new Object();
    
    /**
     * 获取gson对象，解决字符串为null转换为空
     * @return Gson对象实例,日期格式为：yyyy-MM-dd HH:mm:ss
     */
    public static Gson getGson(){
        if(gsonInstance == null) {
            synchronized (LOCK) {
                if (gsonInstance == null) {
                    gsonInstance = new GsonBuilder()
                            .serializeNulls()
                            .setDateFormat("yyyy-MM-dd HH:mm:ss")
                            .registerTypeAdapter(Long.class,new LongJsonAdapter())
                            .registerTypeAdapter(Integer.class,new IntegerJsonAdapter())
                            .registerTypeAdapter(Boolean.class,new BooleanJsonAdapter())
                            .registerTypeAdapter(Float.class,new FloatJsonAdapter())
                            .registerTypeAdapter(Double.class,new DoubleJsonAdapter())
                            .registerTypeAdapter(Short.class,new ShortJsonAdapter())
                            .registerTypeAdapter(Byte.class,new ByteJsonAdapter())
                            .registerTypeAdapterFactory(new SelfCollectionTypeAdapterFactory())
                            .addSerializationExclusionStrategy(new SerializationExclusionStrategyImpl())
                            .addDeserializationExclusionStrategy(new DeserializationExclusionStrategyImpl())
                            .create();
                }
                return gsonInstance;
            }
        }
        return gsonInstance;
    }

    /**
     * 根据当前gson获取新的gsonbuilder
     * @return gsonBuilder
     */
    public static GsonBuilder getNewBuilder(){
        return getGson().newBuilder();
    }
    /**
     * 转换类型为List<T>
     * @param classZ 类
     * @param <T> 类
     * @return type
     */
    public static <T> Type toListType(Class<T> classZ){
        return new TypeToken<List<T>>(){}.getType();
    }

    /**
     * 转换类型为Set<T>
     * @param classZ 类
     * @param <T> 类
     * @return type
     */
    public static <T> Type toSetType(Class<T> classZ){
        return new TypeToken<Set<T>>(){}.getType();
    }
}
